package com.haoshuang.zhouzhoubang.ui.fragment

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Location
import android.net.Uri
import android.os.Bundle
import android.util.Log
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentOrderListStatusBinding
import com.haoshuang.zhouzhoubang.model.bean.FocusDateBean
import com.haoshuang.zhouzhoubang.model.bean.OrderBean
import com.haoshuang.zhouzhoubang.model.event.OrderStatusChangeEvent
import com.haoshuang.zhouzhoubang.model.event.ReceiveOrderSuccess
import com.haoshuang.zhouzhoubang.model.event.RefreshMasterOrderEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshOrderNumEvent
import com.haoshuang.zhouzhoubang.model.event.TransferOrderSuccess
import com.haoshuang.zhouzhoubang.ui.activity.AppointmentCustomerActivity
import com.haoshuang.zhouzhoubang.ui.activity.AppointmentCustomerActivity2
import com.haoshuang.zhouzhoubang.ui.activity.ComfirmDoorInActivity
import com.haoshuang.zhouzhoubang.ui.activity.ExtraCostsPayActivity
import com.haoshuang.zhouzhoubang.ui.activity.MemberConfirmSignActivity
import com.haoshuang.zhouzhoubang.ui.activity.OrderYsActivity
import com.haoshuang.zhouzhoubang.ui.activity.ReturnDetailActivity
import com.haoshuang.zhouzhoubang.ui.activity.ServiceOrderStatusActivity
import com.haoshuang.zhouzhoubang.ui.activity.ShouKuanActivity
import com.haoshuang.zhouzhoubang.ui.activity.SubmitAcceptanceActivity
import com.haoshuang.zhouzhoubang.ui.adapter.FocusDateAdapter
import com.haoshuang.zhouzhoubang.ui.adapter.FocusDateDayAdapter
import com.haoshuang.zhouzhoubang.ui.adapter.FocusDateTitleAdapter
import com.haoshuang.zhouzhoubang.ui.adapter.OrderAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.CheckDialog
import com.haoshuang.zhouzhoubang.ui.dialog.CheckDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.ChooseDateRangeDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowOrderPriceDialog
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.SmDialog3
import com.haoshuang.zhouzhoubang.ui.dialog.YsDialog
import com.haoshuang.zhouzhoubang.ui.page.order.assignment.TaskAssignmentActivity
import com.haoshuang.zhouzhoubang.ui.page.order.contact.ContactWorkerActivity
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.haoshuang.zhouzhoubang.ui.page.order.upload.UploadInServiceActivity
import com.haoshuang.zhouzhoubang.ui.vm.OrderListStatusViewModel
import com.haoshuang.zhouzhoubang.utils.DateTools
import com.haoshuang.zhouzhoubang.utils.LocationUtils
import com.haoshuang.zhouzhoubang.utils.MultiMediaChooseUtils
import com.haoshuang.zhouzhoubang.utils.NavigationUtils
import com.haoshuang.zhouzhoubang.utils.OSSUploadUtils
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.haoshuang.zhouzhoubang.utils.TimeCheckUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.core.setEmptyData
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.core.setupData
import com.mufeng.libs.core.setupEmptyData
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.ktx.formatTen
import com.mufeng.libs.utils.ktx.runOnUIThread
import com.mufeng.libs.utils.ktx.toDateForm
import com.mufeng.libs.utils.ktx.toJson
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.horizontal
import com.mufeng.libs.utils.view.isVisible
import com.mufeng.libs.utils.view.vertical
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import java.util.ArrayList
import java.util.Date


/**
 *
 */
class OrderListStatusFragment :
    BaseVMFragment<OrderListStatusViewModel, FragmentOrderListStatusBinding>() {

    companion object {
        fun getInstance(status: Int, isRework: Int = 0): OrderListStatusFragment {
            val fragment = OrderListStatusFragment()
            fragment.arguments = Bundle().apply {
                putInt("status", status)
                putInt("isRework", isRework)
            }
            return fragment
        }
    }

    private var json = ""

    // 详细状态 8: 待预约, 1: 待上门, 7: 已超时, 2: 服务中, 6: 待验收, 3: 已完成, 4: 退款/售后
    // 1: 待服务, 2: 进行中, 3: 已完成, 4: 退款/售后, 5: 返工单
    private var status = 1

    // 是否是返工单
    private var isRework = 0

    // 完成订单 时间筛选
    private var start_date = ""
    private var end_date = ""
    private var hexiao_type = ""

    // 待上门的时间筛选
    // 0: 自定义, 1: 月份, 2: 天
    private var dateType = 1
    private var date = ""
    private var dateDay = ""

    // 聚焦时间
    private val focusData = arrayListOf<FocusDateBean>()
    private val focusAdapter = FocusDateAdapter(focusData)

    // 非聚焦时间标题
    private val dateTitles = arrayListOf("日", "一", "二", "三", "四", "五", "六")
    private val dateTitleAdapter = FocusDateTitleAdapter(dateTitles)

    // 非聚焦时间
    private val dateDayData = arrayListOf<FocusDateBean>()
    private val dateDayAdapter = FocusDateDayAdapter(dateDayData)

    private val data = arrayListOf<OrderBean>()
    private lateinit var adapter: OrderAdapter

    // 是否执行签到动作
    private var isSignAction = false
    private var currentOrder: OrderBean? = null

    override fun initArgument() {
        status = arguments?.getInt("status") ?: 0
        isRework = arguments?.getInt("isRework") ?: 0
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.llTime.visibleOrGone(isRework == 0 && status == 1)
        binding.tvScreenDate.visibleOrGone(isRework == 0 && status == 3)
        binding.tabSmfw.tvStatus.visibleOrGone(isRework == 0 && status == 3)
        binding.tabDdhx.tvStatus.visibleOrGone(isRework == 0 && status == 3)

        // 上门服务
        binding.tabSmfw.tvStatus.text = "上门服务"
        // 到店核销
        binding.tabDdhx.tvStatus.text = "到店核销"
        binding.tabSmfw.tvStatus.isSelected = true

        binding.tabSmfw.tvStatus.clickWithTrigger {
            binding.tabSmfw.tvStatus.isSelected = true
            binding.tabDdhx.tvStatus.isSelected = false
            hexiao_type = ""

            p = 1
            isShowing = false
            getData()
            LiveEventBus.get(RefreshOrderNumEvent::class.java).post(RefreshOrderNumEvent)
        }
        binding.tabDdhx.tvStatus.clickWithTrigger {
            binding.tabSmfw.tvStatus.isSelected = false
            binding.tabDdhx.tvStatus.isSelected = true
            hexiao_type = "2"

            p = 1
            isShowing = false
            getData()
            LiveEventBus.get(RefreshOrderNumEvent::class.java).post(RefreshOrderNumEvent)
        }


        if (binding.llTime.isVisible) {
            date = "${Date().toDateForm("yyyy-MM")}"
            binding.tvCheckTime.text = date
            binding.ivCheck.isSelected = true
            binding.ivCheck.click {
                if (!binding.ivCheck.isSelected) {
                    dateType = 1
                    binding.ivCheck.isSelected = true
                    binding.rvFocusDate.visible()
                    binding.rvDateTitle.gone()
                    binding.rvDateDay.gone()
                    binding.refreshLayout.autoRefresh()
                } else {
                    dateType = 2
                    binding.ivCheck.isSelected = false
                    binding.rvFocusDate.gone()
                    binding.rvDateTitle.visible()
                    binding.rvDateDay.visible()
                    if (dateDay.isNotEmpty()) {
                        binding.refreshLayout.autoRefresh()
                    }
                }
            }

            binding.tvCheckTime.clickWithTrigger {
                // 选择日期
                TimeCheckUtils.newInstance().getTime(mActivity) {
                    date = it
                    dateDay = ""
                    binding.tvCheckTime.text = date
                    dateType = 1
                    binding.ivCheck.isSelected = true
                    binding.rvFocusDate.visible()
                    binding.rvDateTitle.gone()
                    binding.rvDateDay.gone()
                    vm.getMasterCalendar(status, date)
                    binding.refreshLayout.autoRefresh()
                }
            }

            binding.rvFocusDate.horizontal().adapter = focusAdapter
            binding.rvDateTitle.vertical(7).adapter = dateTitleAdapter
            binding.rvDateDay.vertical(7).adapter = dateDayAdapter
            dateDayAdapter.setOnItemClick { view, position, item ->
                if (item == null) return@setOnItemClick
                if (item.date?.isEmpty() == true) {
                    return@setOnItemClick
                }
                dateDay = item.date.toString()
                dateDayData.forEach {
                    if (it.date == item.date) {
                        it.isCheck = 1
                    } else {
                        it.isCheck = 0
                    }
                }
                dateDayAdapter.notifyDataSetChanged()
                // 请求数据获取订单列表
                binding.refreshLayout.autoRefresh()
            }

        }

        binding.tvScreenDate.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(ChooseDateRangeDialog(mActivity) { startDate, endDate ->
                    start_date = startDate
                    end_date = endDate
                    binding.tvScreenDate.text = "$start_date ~ $end_date"
                    binding.refreshLayout.autoRefresh()
                })
                .show()
        }

        adapter = OrderAdapter(data, status)
        binding.recyclerView.vertical().adapter = adapter

        adapter.setOnItemClick { view, position , item->
            if (item == null) return@setOnItemClick

            // 打开订单详情
            startPageForResult<ServiceOrderStatusActivity>(
                "ids" to item.id,
                "is_rework" to (isRework == 1)
            ) { code, data ->
                if (code == 200) {
                    binding.refreshLayout.autoRefresh()
                }
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvContactWorker){view, position, item ->
            // 联系工人
            startPage<ContactWorkerActivity>("order_id" to item?.id.toString())
        }

        adapter.setOnItemChildClick(id = R.id.ivCallPhone){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 拨打电话
            if (item.user_phone.isBlank()) {
                toast("电话不能为空")
            }
            mActivity.callPhone(item.user_phone)
        }
        adapter.setOnItemChildClick(id = R.id.ivNavigation){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 地图导航
            if (item.lat.isBlank()) {
                toast("经纬度不能为空")
                return@setOnItemChildClick
            }
            NavigationUtils.startNavigation(
                mActivity,
                item.lat,
                item.lng,
                item.user_address
            )
        }
        adapter.setOnItemChildClick(id = R.id.tvPayPrice){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 查看价格详情
            // 订单价格
            // 判断角色 1团长2团队负责人3团队成员4普通用户

            val teamPrice = item.team_price?.team_price
            val teamLeaderPrice = item.team_price?.team_leader_price
            val teamMemberPrice = item.team_price?.team_member_price
            val minePrice = item.team_price?.self_price
            XPopup.Builder(mActivity)
                .asCustom(
                    ShowOrderPriceDialog(
                        context = mActivity,
                        prepayments_amount = item.prepayments_amount.toString(),
                        nightPrice = "${item.nighttime_amount}",
                        totalPrice = item.pay_price,
                        teamPrice = teamPrice ?: "",
                        teamLeaderPrice = teamLeaderPrice ?: "",
                        teamMemberPrice = teamMemberPrice ?: item.pay_price,
                        minePrice = minePrice ?: item.pay_price,
                    )
                )
                .show()
        }
        adapter.setOnItemChildClick(id = R.id.tvPayment) { view, position, item ->
            // 付款
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 收款
            startPage<ShouKuanActivity>(
                "team_id" to item.order_id,
                "serviceName" to item.store_name
            )
        }
        adapter.setOnItemChildClick(id = R.id.tvTaskAssignment){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 任务指派
            startPageForResult<TaskAssignmentActivity>(
                "ids" to item.id.toString(),
                "is_rework" to (isRework == 1),
                "isPersonal" to (item.is_team != "1")
            ) { code, data ->
                if (code == 200) {
                    binding.refreshLayout.autoRefresh()
                }
            }
        }

        adapter.setOnItemChildClick(duration = 1000,id = R.id.tvSign) { view, position, item ->
            // 点击签到
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            if (item.is_sign == 0) {
                // 获取定位
                isShowing = true
                showLoading()
                getLocation { lat, lng ->
                    dismissLoading()
                    LocationUtils.unregister()
                    // 判断是否可以确认上门
                    currentOrder = item
                    isSignAction = true
                    vm.isConfirmDoorVisit(
                        item.id.toString(),
                        lat.toString(),
                        lng.toString()
                    )
                }
            }
        }

        adapter.setOnItemChildClick(duration = 1000, id = R.id.tvConfirmService) { view, position, item ->
            // 开始服务 确认上门
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            isSignAction = false
            currentOrder = item
            vm.getMasterOrderDetail(item.id.toString())
        }

        // 确认服务
        adapter.setOnItemChildClick(id = R.id.tvConfirmedService){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            startPageForResult<ComfirmDoorInActivity>(
                "ids" to item.id,
                "is_rework" to (isRework == 1)
            ) { code, data ->
                if (code == 200) {
                    binding.refreshLayout.autoRefresh()
                }
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvContactCustomers){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 联系客户
            if (item.is_team == "0") {
                startPage<AppointmentCustomerActivity>(
                    "ids" to item.id,
                    "user_status" to item.user_status,
                    "is_rework" to (isRework == 1)
                )
            } else {
                startPage<AppointmentCustomerActivity2>(
                    "ids" to item.id,
                    "user_status" to item.user_status,
                    "is_rework" to (isRework == 1)
                )
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvUpdateTime){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            startPageForResult<UpdateServiceTimeActivity>("cate_id" to item.cate_id){code, data ->
                if (code == Activity.RESULT_OK){
                    if (data != null) {
                        val service_day = data.getStringExtra("service_day").toString()
                        val service_day1 = data.getStringExtra("service_day1")
                        val service_time = data.getStringExtra("service_time").toString()
                        vm.confirmUpdateServiceTime(
                            item.id.toString(),
                            service_day.toString(),
                            service_time.toString()
                        )
                    }
                }
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvUploadImage) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            // 上传服务中图片
            currentOrder = item
//            addInServiceImg()
            startPageForResult<UploadInServiceActivity>("orderId" to item.id.toString()){ code, data ->
                if (code == 200) {
                    binding.refreshLayout.autoRefresh()
                }
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvSubmitAcceptance) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            // 提交验收
            currentOrder = item
            json = ""
            vm.getOtherCost(item.id.toString())
            if (item.cost_list.size > 0) {
                json = item.cost_list.toJson()
            }
        }

        adapter.setOnItemChildClick(id = R.id.tvReminderAcceptance) { view, position, item ->
            // 提醒验收
            if (item == null) return@setOnItemChildClick
            if (AccountUtils.canReminderUserAcceptanceTime(item.id.toString())){
                vm.remindCheck(item.id.toString())
            }else{
                XPopup.Builder(mActivity)
                    .asCustom(ConfirmDialog(
                        context =mActivity,
                        title = "温馨提示",
                        content = "5分钟内只能提醒一次, 请稍后再试",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        isHideAgain = false,
                        onCancel = {},
                        onConfirm = {}))
                    .show()
            }

        }

        adapter.setOnItemChildClick(id = R.id.tvAcceptanceQRCode) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            // 查看验收码
            vm.checkOrder(item.id.toString())
        }

        adapter.setOnItemChildClick(id = R.id.tvImmediateProcessing){view, position, item ->
            if (item == null) return@setOnItemChildClick
            currentOrder = item
            // 立即处理
            when (item.status) {
                "4" -> {//服务完成
                    if (item.refund_id != "0") {
                        startPageForResult<ReturnDetailActivity>(
                            "ids" to item.id,
                            "is_rework" to (isRework == 1)
                        ){code, data ->
                            vm.getMasterOrderList(
                                status,
                                p,
                                if (dateType == 2) dateDay else date,
                                dateType,
                                "",
                                isRework,
                                start_date,
                                end_date,
                            )
                        }
                    }

                }
            }
        }

        // 8: 待确认, 1: 待上门, 7: 已超时, 2: 服务中, 6: 待验收, 3: 已完成, 4: 退款/售后
        if (isRework == 0) {
            when (status) {
                1 -> {
                    if (isRework == 0) {
                        adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无待上门订单")
                    } else {
                        adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无待上门订单")
                    }
                }

                2 -> adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无服务中订单")
                3 -> adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无已完成订单")
                4 -> adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无退款/售后订单")
                6 -> adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无待验收订单")
                7 -> adapter.setEmptyData(
                    R.mipmap.icon_empty_order,
                    "暂无超时订单",
                    "指的是待确定上门超时订单，需要尽快完成"
                )

                8 -> adapter.setEmptyData(
                    R.mipmap.icon_empty_order,
                    "暂无待确认订单",
                    "指的是您接单后需要在规定时间内预约客户确认订单"
                )

                else -> adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无订单")
            }
        } else {
            adapter.setEmptyData(R.mipmap.icon_empty_order, "暂无返工单")
        }

        binding.refreshLayout.setOnRefreshListener {
            p = 1
            isShowing = false
            getData()
            LiveEventBus.get(RefreshOrderNumEvent::class.java).post(RefreshOrderNumEvent)
        }

        binding.refreshLayout.setOnLoadMoreListener {
            p++
            isShowing = false
            getData()
        }

    }

    /**
     * 上传服务中图片/视频
     */
    private fun addInServiceImg() {
        XPopup.Builder(requireContext())
            .asCustom(CheckDialog(requireContext()) {
                when (it) {
                    "0" -> {
                        XPopup.Builder(requireContext())
                            .asCustom(CheckDialog2(requireContext()) {
                                addImage(
                                    requireContext(),
                                    0, it
                                )
                            })
                            .show()
                    }

                    "1" -> {
                        XPopup.Builder(requireContext())
                            .asCustom(CheckDialog2(requireContext()) {
                                addVideo(it)
                            })
                            .show()
                    }
                }
            })
            .show()
    }

    private fun addImage(
        context: Context,
        imageNum: Int,
        s: String
    ) {
        if (s == "0") {
            // 拍照
            MultiMediaChooseUtils.cameraMultiMedia(
                context =mActivity,
                isVideo = false,
                permissionTitle = "权限使用说明",
                permissionContent = "拍摄照片并上传",
                onChoose = {
                    if (it == null) return@cameraMultiMedia
                    setUrl(arrayListOf(it), 0)
                })
        } else {
            // 选择图片
            MultiMediaChooseUtils.checkImage(
                context =mActivity,
                num = 9 - imageNum,
                permissionTitle = "权限使用说明",
                permissionContent = "选择图片并上传",
                onChoose = {
                    setUrl(it, 0)
                })
        }

    }

    private fun addVideo(s: String) {
        if (s == "0") {
            MultiMediaChooseUtils.cameraMultiMedia(
                context =mActivity,
                isVideo = true,
                permissionTitle = "权限使用说明",
                permissionContent = "录制视频并上传",
                onChoose = {
                    if (it == null) return@cameraMultiMedia
                    setUrl(arrayListOf(it), 1)
                })
        } else {
            MultiMediaChooseUtils.chooseMultiMedia(
                context =mActivity,
                isVideo = true,
                permissionTitle = "权限使用说明",
                permissionContent = "选择视频并上传",
                onChoose = {
                    if (it == null) return@chooseMultiMedia
                    setUrl(arrayListOf(it), 1)
                })
        }

    }

    private fun setUrl(result: MutableList<LocalMedia>, type: Int) {
        OSSUploadUtils.uploadFiles(
            "userSetting/feedback",
            result.map { it.realPath }.toMutableList()
        ) {
            start {
                isShowing = true
                runOnUIThread { showLoading() }
            }
            error { clientException, serviceException ->
                runOnUIThread {
                    dismissLoading()
                    toast("上传失败")
                }
            }
            successAll {
                // 全部上传成功
                runOnUIThread {
                    dismissLoading()
                    if (type == 1) {
                        // 上传视频
                        vm.doService(currentOrder?.id.toString(), "", it?.first().toString())
                    } else {
                        // 上传图片
                        vm.doService(
                            currentOrder?.id.toString(),
                            it?.joinToString(",").toString(),
                            ""
                        )
                    }
                }
            }
        }
    }

    override fun initData() {


    }
    fun refreshData(){
        binding.refreshLayout.autoRefresh()
        if (isRework == 0 && status == 1) {
            // 请求聚焦数据
            vm.getMasterCalendar(status, date)
        }
    }
    private fun getData() {
        vm.getMasterOrderList(
            status,
            p,
            if (dateType == 2) dateDay else date,
            dateType,
            "",
            isRework,
            start_date,
            end_date,hexiao_type
        )
    }

    override fun lazyLoadData() {
        if (isRework == 0 && status == 1) {
            // 请求聚焦数据
            vm.getMasterCalendar(status, date)
        }
        binding.refreshLayout.autoRefresh()
    }

    override fun onResume() {
        super.onResume()
        refreshData()
    }

    override fun startObserve() {

        LiveEventBus.get(ReceiveOrderSuccess::class.java).observe(this){
            // 抢单成功刷新
            binding.refreshLayout.autoRefresh()
        }

        // 刷新列表数据
        LiveEventBus.get(RefreshMasterOrderEvent::class.java).observe(this) {
            binding.refreshLayout.autoRefresh()
        }

        // 转单成功刷新
        LiveEventBus.get(TransferOrderSuccess::class.java).observe(this) {
            // 刷新列表数据
            binding.refreshLayout.autoRefresh()
        }

        vm.getMasterCalendarData.observeState(this) {
            onSuccess {
                dismissLoading()
                focusData.clear()
                focusData.addAll(it ?: mutableListOf())
                focusAdapter.notifyDataSetChanged()
                dateDayData.clear()
                dateDayData.addAll(getDateDayList(it))
                dateDayAdapter.notifyDataSetChanged()
            }
        }

        vm.getMasterOrderListData.observeState(this) {
            onLoading { }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.setupEmptyData(data, adapter, p)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.setupData(it, data, adapter, p)
            }
        }

        vm.isConfirmDoorVisitData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                if (isSignAction) {
                    isSignAction = false
                    currentOrder = null
                    XPopup.Builder(mActivity)
                        .asCustom(
                            SmDialog(
                                mActivity,
                                "您未到达用户下单地址 请到达用户下单地址在确认签到"
                            ) {})
                        .show()
                } else {
                    XPopup.Builder(mActivity)
                        .asCustom(
                            SmDialog(
                                mActivity,
                                "您未到达用户下单地址 请到达用户下单地址在确认上门"
                            ) {

                            })
                        .show()
                }

            }
            onSuccess {
                dismissLoading()
                if (isSignAction) {
                    // 签到
                    isSignAction = false
                    XPopup.Builder(mActivity)
                        .asCustom(
                            SmDialog3(
                                mActivity,
                                "上门地址:${it?.user_address}",
                                currentOrder?.insurance_status == "1"
                            ) {
                                // 打开确认签到页面
                                startPageForResult<MemberConfirmSignActivity>("order_id" to currentOrder?.id.toString()) { code, data ->
                                    if (code == 200) {
                                        binding.refreshLayout.autoRefresh()
                                        currentOrder = null
                                    }
                                }
                            })
                        .show()
                } else {
                    // 确认上门
                    XPopup.Builder(mActivity)
                        .asCustom(
                            SmDialog2(
                                mActivity,
                                "上门地址:${it?.user_address}",
                                currentOrder?.insurance_status == "1"
                            ) {
                                // 调用确认上门接口
                                vm.confirmDoor(currentOrder?.id.toString())
                            })
                        .show()
                }
            }
        }

        // 确认上门
        vm.confirmDoorData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                // 跳转到上门中
                if (isRework == 1){
                    LiveEventBus.get(OrderStatusChangeEvent::class.java)
                        .post(OrderStatusChangeEvent(5, 10))
                }else {
                    LiveEventBus.get(OrderStatusChangeEvent::class.java)
                        .post(OrderStatusChangeEvent(2, 10))
                }
                binding.refreshLayout.autoRefresh()
                startPageForResult<ComfirmDoorInActivity>(
                    "ids" to currentOrder?.id,
                    "is_rework" to (isRework == 1)
                ) { code, data ->
                    if (code == 200) {
                        binding.refreshLayout.autoRefresh()
                    }
                }
            }
        }

        vm.confirmUpdateServiceTimeData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                // 上门时间修改成功 跳转到待上门
                LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(1,1))
                LiveEventBus.get(RefreshMasterOrderEvent::class.java)
                    .post(RefreshMasterOrderEvent())
                binding.refreshLayout.autoRefresh()
            }
        }

        vm.getMasterOrderDetailData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    // 获取是否有未签到的成员
                    val filter = it.team_member.filter { it.team_is_sign != "1" }
                    if (filter.isEmpty()) {
                        // 全部签到
                        isShowing = true
                        showLoading()
                        getLocation { lat, lng ->
                            dismissLoading()
                            LocationUtils.unregister()
                            // 获取定位 经纬度
                            vm.isConfirmDoorVisit(
                                currentOrder?.id.toString(),
                                lat.toString(),
                                lng.toString()
                            )
                        }
                    } else {
                        // 有未签到的成员
                        XPopup.Builder(mActivity)
                            .asCustom(
                                SmDialog(
                                    mActivity,
                                    "当前还有${filter.size}名队员未签到，请联系当事人签到！"
                                ) {

                                })
                            .show()
                    }
                }
            }
        }

        vm.checkOrderData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    startPage<OrderYsActivity>(
                        "finish_status" to it.finish_status,
                        "qrcode_url" to it.qrcode_url,
                        "orderId" to it.orderId
                    )
                }
            }
        }

        vm.doServiceData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("上传成功")
            }
        }

        vm.getOtherCostData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if ((it?.total_price?.toDoubleOrNull() ?: 0.0) > 0) {
                    var content = "当前订单有一笔额外费用客户未支付\n" +
                            "请联系客户支付后在提交验收"
                    if (currentOrder?.paid != "1") {
                        content =
                            "当前订单有额外费用和订单金额客户\n未支付请联系客户支付后在提交验收"
                        XPopup.Builder(mActivity)
                            .asCustom(YsDialog(requireContext(), content) {
                                startPage<ShouKuanActivity>(
                                    "team_id" to currentOrder?.order_id.toString(),
                                    "serviceName" to currentOrder?.store_name
                                )
                            })
                            .show()
                    } else {
                        XPopup.Builder(mActivity)
                            .asCustom(YsDialog(mActivity, content) {
                                startPage<ExtraCostsPayActivity>(
                                    "orderId" to currentOrder?.id.toString(),
                                    "payName" to "额外费用"
                                )
                            })
                            .show()
                    }
                } else {
                    if (currentOrder?.paid != "1") {
                        val content = "当前订单有订单金额客户未支付\n请联系客户支付后在提交验收"
                        XPopup.Builder(mActivity)
                            .asCustom(YsDialog(requireContext(), content) {
                                startPage<ShouKuanActivity>(
                                    "team_id" to currentOrder?.order_id.toString(),
                                    "serviceName" to currentOrder?.store_name
                                )
                            })
                            .show()
                    } else {
                        startPageForResult<SubmitAcceptanceActivity>(
                            "ids" to currentOrder?.id,
                            "json" to json,
                            "is_rework" to true
                        ) { code, data ->
                            if (code == 200) {
                                binding.refreshLayout.autoRefresh()
                            }
                        }
                    }
                }
            }
        }

        vm.remindCheckData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("提醒成功")
                AccountUtils.setReminderUserAcceptanceTime(it.toString())
            }
        }
    }

    private fun getDateDayList(focusDateBeans: MutableList<FocusDateBean>?): MutableList<FocusDateBean> {
        val dateDayList = mutableListOf<FocusDateBean>()
        val monthDays =
            DateTools.getMonthOfDay(date.split("-")[0].toInt(), date.split("-")[1].toInt())
        val firstDayWeek =
            DateTools.getFirstDayWeek(date.split("-")[0].toInt(), date.split("-")[1].toInt())
        if (firstDayWeek != 1) {
            // 添加空白数据
            for (i in 0 until firstDayWeek - 1) {
                dateDayList.add(FocusDateBean(date = "", list = null, day = "", isCheck = 0))
            }
        }
        for (b in 0 until monthDays) {
            dateDayList.add(
                FocusDateBean(
                    "${date}-${(b + 1).formatTen()}",
                    (b + 1).toString(),
                    null,
                    0
                )
            )
        }
        focusDateBeans?.forEach { focusDateBean ->
            for (focusDateBean1 in dateDayList) {
                if (focusDateBean1.date == focusDateBean.date) {
                    focusDateBean1.list = focusDateBean.list
                }
            }
        }

        return dateDayList
    }

    fun getOrderStatus(): Int {
        if (isRework == 1) return 5
        return status
    }

    private fun getLocation(locationSuccess: (lat: Double?, lng: Double?) -> Unit) {
        PermissionHelper.requestPermission(
            mActivity,
            "位置权限使用说明",
            "服务确认上门需要获取您当前的位置, 方便您更好的为客户服务",
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) { allGranted ->
            if (allGranted) {
                LocationUtils.register(
                    mActivity,
                    1000,
                    0,
                    object : LocationUtils.OnLocationChangeListener {
                        override fun getLastKnownLocation(location: Location?) {
                            Log.e("xyh", "onLocationChanged: " + location?.latitude)
                        }

                        override fun onLocationChanged(location: Location?) {
                            val lat = location?.latitude
                            val lng = location?.longitude
                            locationSuccess(lat, lng)
                            LocationUtils.unregister()
                        }

                        override fun onStatusChanged(
                            provider: String?,
                            status: Int,
                            extras: Bundle?
                        ) {

                        }
                    })
            }
        }


    }

}